export default defineNuxtPlugin(nuxtApp => {
  const useStore = useUserStore()

  const request = $fetch.create({
    baseURL: '/',
    onRequest({ /* request, error,*/ options }) {
      if (useStore.token) {
        // 请注意，这依赖于 ofetch >= 1.4.0 - 可能需要刷新您的锁文件
        options.headers.set('Authorization', `Bearer ${useStore.token}`)
      }
      options.params = { ...options.params, _t: Date.now() }
      // options.body
    },
    async onResponseError({ response }) {
      if (response.status === 401) {
        await nuxtApp.runWithContext(() => navigateTo('/login'))
        // reloadNuxtApp() // 重载 Nuxt 应用
      }
    }
  })

  // 暴露给 useNuxtApp().$request
  return {
    provide: {
      request
    }
  }
})

/**
<script setup>
const { $request } = useNuxtApp()
const { data: modules } = await useAsyncData('modules', () => $request('/modules'))
</script>
 */
